package home

import (
	"github.com/gin-gonic/gin"

	"github.com/zeromicro/go-zero/tools/goctl/example/api/internal/domain"
	"github.com/zeromicro/go-zero/tools/goctl/example/api/internal/logic"
	"github.com/zeromicro/go-zero/tools/goctl/example/api/internal/svc"
	"github.com/zeromicro/go-zero/tools/goctl/example/api/pkg/httpx"
)

type Common struct {
	svcCtx *svc.ServiceContext
	common logic.Common
}

func NewCommon(svcCtx *svc.ServiceContext, common logic.Common) *Common {
	return &Common{
		svcCtx: svcCtx,
		common: common,
	}
}

func (h *Common) InitRegister(engine *gin.Engine) {
	g := engine.Group("v1/common")
	g.POST("/upload", h.Upload)
	g.GET("/download", h.Download)
	g.GET("/captcha", h.Captcha)
}

func (h *Common) Upload(ctx *gin.Context) {
	var req domain.UploadReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	res, err := h.common.Upload(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}

func (h *Common) Download(ctx *gin.Context) {
	var req domain.DownloadReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	err := h.common.Download(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.Ok(ctx)
	}
}

func (h *Common) Captcha(ctx *gin.Context) {
	var req domain.CaptchaReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	res, err := h.common.Captcha(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}
